<?php

class SettingsController extends AppController {

    public function beforeFilter() {
        parent::beforeFilter();
        
        $exclusions = array('keep_alive');
        
        if( !in_array($this->params['action'], $exclusions) ) {
            // check if user is not authenticated and request login
            $this->validateOrganisationAccount();

            // check if we have an org account and if the role has admin access
            if( $this->Session->check('org_account') ) {
                $org_account = $this->Session->read('org_account');

                if( !$org_account['OrganisationRole']['admin_access'] ) {
                    $this->redirect('/' . $this->params['organisationSlug']);
                }
            }
        }
    }
    
    public function keep_alive() {
        $this->autoRender = false;
        $response = array();
        
        if( $this->Session->check('org_account') ) {
            $orgAccount = $this->Session->read('org_account');
            $response = array('session_status' => 'active', 'org_account' => $orgAccount);
        }
        
        else {
            $response = array('session_status' => 'inactive');
        }
        
        return json_encode($response);
    }

    public function groups() {
        $this->layout = 'admin_settings';

        $orgAccount = $this->Session->read('org_account');

        $categories = $this->Api->post('/groups/types', array(
            'organisation_id' => $orgAccount['Organisation']['id']
        ));

        $title_for_layout = "Small Groups";

        $this->set(compact('categories', 'title_for_layout'));
    }
    
    public function group_details() {
        $this->layout = 'ajax';
        
        $orgAccount = $this->Session->read('org_account');
        
        if( $this->request->is('post') ) {
            $data = $this->request->data;
            
            if( isset($data['action']) && $data['action'] == 'add_group_leader' ) {
                $this->autoRender = false;
                
                $result = $this->Api->post('/groups/leaders/save', array(
                    'organisation_id' => $orgAccount['Organisation']['id'],
                    'organisation_group_id' => $data['organisation_group_id'],
                    'organisation_member_id' => $data['organisation_member_id'],
                    'role' => $data['role']
                ));
                
                return json_encode($result);
            }
            
            else if( isset($data['action']) && $data['action'] == 'remove_group_leader' ) {
                $this->autoRender = false;
                
                $result = $this->Api->post('/groups/leaders/remove', array(
                    'organisation_id' => $orgAccount['Organisation']['id'],
                    'organisation_group_leader_id' => $data['leader_id']
                ));
                
                return json_encode($result);
            }
            
            else if( isset($data['group_id']) ) {
                $response = $this->Api->post('/groups/group', array(
                    'organisation_id' => $orgAccount['Organisation']['id'],
                    'group_id' => $data['group_id']
                ));

                $this->set('group', $response);
            }
        }
    }
    
    public function anniversaries() {
        $this->layout = 'admin_settings';

        $orgAccount = $this->Session->read('org_account');
        
        $dates = $this->Api->post('/dates/', array(
            'organisation_id' => $orgAccount['Organisation']['id']
        ));

        $title_for_layout = "Special Anniversaries";

        $this->set(compact('dates', 'title_for_layout'));
    }

    public function general() {

        $this->layout = 'admin_settings';

        $orgAccount = $this->Session->read('org_account');

        if (isset($_POST['Organisation'])) {
            $this->autoRender = false;

            $result = $this->Api->post("/organisation/update", array(
                'organisation_id' => $orgAccount['Organisation']['id'],
                'info' => $_POST
            ));

            // update the session information
            //$orgAccount['Organisation'] = $_POST['Organisation'];
            //$this->Session->write('org_account', $orgAccount);
            // clear the organisation slugs cache so it gets updated if the slug has changed
            Cache::delete('organisation_slugs');

            return json_encode($result);
        }

        $batch = $this->Api->post('/batch', array(
            'organisation' => array(
                'url' => '/organisation',
                'method' => 'post',
                'params' => array(
                    'organisation_id' => $orgAccount['Organisation']['id'],
                    'contain' => array('OrganisationType')
                )
            )
        ));
        
        extract($batch);

        $title_for_layout = "Organisation Profile";

        $this->set(compact('organisation', 'title_for_layout'));
    }
    
    public function roles() {
        $this->layout = 'admin_settings';

        $orgAccount = $this->Session->read('org_account');
        
        // handle requests
        if( $this->request->is('ajax') && $this->request->is('post') ) {
            $this->autoRender = false;
            
            $data = $this->request->data;
            
            if( isset($data['action']) && $data['action'] == 'delete' ) {
                $response = $this->Api->post('/organisation/role/delete', array(
                    'organisation_id' => $orgAccount['Organisation']['id'],
                    'role_id' => $data['role_id']
                ));
            }
            
            else {
                $data['organisation_id'] = $orgAccount['Organisation']['id'];
                $response = $this->Api->post('/organisation/role/update', $data);
            }
            
            return json_encode($response);
        }
        
        // load page
        $modules = $this->Api->post('/system/modules');
        $this->set('modules', $modules);
        
        $response = $this->Api->post("/organisation/role/list", array(
            'organisation_id' => $orgAccount['Organisation']['id']
        ));
        
        if( $response['status'] == 'success' ) {
            $this->set('roles', $response['roles']);
        }
        
        $title_for_layout = "Organisation Roles";
        
        $this->set(compact('modules', 'title_for_layout'));
    }
    
    public function role() {
        $this->autoRender = false;
        
        $orgAccount = $this->Session->read('org_account');
        
        if( $this->request->is('ajax') && $this->request->is('post') ) {
            $data = $this->request->data;
            
            if( isset($data['role_id']) ) {
                $response = $this->Api->post('/organisation/role', array(
                    'organisation_id' => $orgAccount['Organisation']['id'],
                    'role_id' => $data['role_id']
                ));
                
                return json_encode($response);
            }
        }
    }

    public function categories() {

        $this->layout = 'admin_settings';

        $orgAccount = $this->Session->read('org_account');

        $categories = $this->Api->post("/organisation/categories", array(
            'organisation_id' => $orgAccount['Organisation']['id']
        ));

        $title_for_layout = "Membership Categories";

        $this->set(compact('categories', 'category', 'sys_categories', 'title_for_layout'));
    }

    /**
     * Displays an editor that edits or creates a new category
     * 
     * @param type $category_id
     * @return type
     */
    public function category($category_id = null) {

        $this->layout = "ajax";

        $orgAccount = $this->Session->read('org_account');

        // if form is saved and posted
        if (isset($_POST['OrganisationMemberCategory']['id'])) {
            $this->autoRender = false;

            $data = $_POST;

            foreach ($data['OrganisationMemberCategorySetting'] as &$setting) {
                if (!isset($setting['value'])) {
                    $setting['value'] = 0;
                }
            }

            $response = $this->Api->post('/organisation/category/update', array(
                'organisation_id' => $orgAccount['Organisation']['id'],
                'category' => $data
            ));

            return json_encode($response);
        }

        // if category_id is specified, then fetch information
        if ($category_id == 'delete' && isset($_POST['category_id'])) {
            $this->autoRender = false;

            $result = $this->Api->post('/organisation/category/delete', array(
                'organisation_id' => $orgAccount['Organisation']['id'],
                'category_id' => $_POST['category_id']
            ));

            return json_encode($result);
        }

        if ($category_id) {
            $category = $this->Api->post('/organisation/category', array(
                'organisation_id' => $orgAccount['Organisation']['id'],
                'category_id' => $category_id
            ));

            $this->set(compact('category'));
        }

        $settings = $this->Api->post('/system/category_settings');

        $this->set(compact('settings'));
    }

    public function category_detail($category_id) {

        $this->layout = "ajax";

        $orgAccount = $this->Session->read('org_account');

        $category = $this->Api->post('/organisation/category', array(
            'organisation_id' => $orgAccount['Organisation']['id'],
            'category_id' => $category_id
        ));

        $this->set(compact('category'));
    }

    public function account_detail() {
        $this->layout = 'ajax';

        $orgAccount = $this->Session->read('org_account');

        $response = $this->Api->post("/organisation/account", array(
            'organisation_id' => $orgAccount['Organisation']['id'],
            'account_id' => $_POST['account_id']
        ));
        
        $account = $response['account'];

        $this->set(compact('account'));
    }
    
    public function accounts($action = '') {
        
        $this->layout = 'admin_settings';

        $orgAccount = $this->Session->read('org_account');
        
        if( $this->request->is('ajax') && $this->request->is('post') ) {
            $this->autoRender = false;
            
            $response = $this->Api->post('/organisation/accounts/batch_update', array(
                'organisation_id' => $orgAccount['Organisation']['id'],
                'accounts' => $this->request->data
            ));
            
            return json_encode($response);
        }

        $accounts = $this->Api->post("/organisation/accounts", array(
            'organisation_id' => $orgAccount['Organisation']['id']
        ));
        
        $response = $this->Api->post("/organisation/role/list", array(
            'organisation_id' => $orgAccount['Organisation']['id']
        ));
        
        if( $response['status'] == 'success' ) {
            $this->set('roles', $response['roles']);
        }

        $title_for_layout = "Accounts";

        $this->set(compact('accounts', 'title_for_layout'));
    }

    public function account($action = null) {
        $this->layout = 'ajax';

        $orgAccount = $this->Session->read('org_account');

        if ($action == 'add' && isset($_POST['OrganisationAccount']) && is_array($_POST['OrganisationAccount'])) {
            $this->autoRender = false;

            $_POST['organisation_id'] = $orgAccount['Organisation']['id'];

            $response = $this->Api->post('/organisation/account/update', $_POST);

            return json_encode($response);
        } 
        
        else if ($action == 'delete' && isset($_POST['account_id']) && is_numeric($_POST['account_id']) ) {
            $this->autoRender = false;

            $result = $this->Api->post('/organisation/account/delete', array(
                'organisation_id' => $orgAccount['Organisation']['id'],
                'account_id' => $_POST['account_id']
            ));

            return json_encode($result);
        } 
        
        else if (isset($_POST['account_id'])) {

            $account = $this->Api->post("/organisation/account", array(
                'organisation_id' => $orgAccount['Organisation']['id'],
                'account_id' => $_POST['account_id']
            ));

            $this->set(compact('account'));
        } 
        
        else if ($action == 'checkAvailability' && isset($_POST['username'])) {
            $this->autoRender = false;

            $info = $this->Api->post('/organisation/account/checkAvailability', array(
                'organisation_id' => $orgAccount['Organisation']['id'],
                'username' => $_POST['username']
            ));

            return json_encode($info);
        }
        
        else if( $action == 'lookup' && $this->request->is('ajax') && $this->request->is('get') ) {
            $this->autoRender = false;
            $data = $this->request->query;
            
            if( isset($data['term']) ) {
                $response = $this->Api->post('/organisation/account/lookup', array(
                    'organisation_id' => $orgAccount['Organisation']['id'],
                    'term' => $data['term']
                ));
                
                if( $response['status'] == 'success' ) {
                    return json_encode($response['data']);
                }
                
                return json_encode(array());
            }
        }


        $response = $this->Api->post("/organisation/account/roles", array(
            'organisation_id' => $orgAccount['Organisation']['id']
        ));
        
        if( $response['status'] == 'success' ) {
            $this->set('roles', $response['roles']);
        }
    }

    public function subscription() {
        $this->layout = 'settings';
    }

    public function preferences() {
        $this->layout = 'admin_settings';

        $orgAccount = $this->Session->read('org_account');

        if (isset($_POST['OrganisationSetting'])) {
            $data = $_POST;

            foreach ($data['OrganisationSetting'] as &$d) {
                if (!isset($d['value'])) {
                    $d['value'] = 0;
                }

                $d['organisation_id'] = $orgAccount['Organisation']['id'];
                ClassRegistry::init('OrganisationSetting')->save($d);
            }

            $this->Session->setFlash("Preferences Updated Successfully");
        }

        $preferences = $this->Api->post("/organisation/preferences", array(
            'organisation_id' => $orgAccount['Organisation']['id']
        ));

        $title_for_layout = "Preferences";

        $this->set(compact('preferences', 'title_for_layout'));
    }

}
